﻿package controllers.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rbac.models.Menu;
import rbac.models.Oplog;
import rbac.models.User;

import com.et.mvc.JsonView;
import com.et.mvc.View;

import controllers.ApplicationController;

public class MenuController extends ApplicationController {

	public void index() throws Exception {

	}

	public View getTreeItems() throws Exception {
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		Map<String, Object> node = new HashMap<String, Object>();
		node.put("id", 0);
		node.put("text", "根目录");
		result.add(node);
		List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();

		List<Menu> menus = Menu.findAll(Menu.class, "parentid=0", null, "sort");
		for (Menu menu : menus) {
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("id", menu.getId());
			item.put("text", menu.getName());
			items.add(item);
		}

		List<Map<String, Object>> doing = new ArrayList<Map<String, Object>>();
		doing.addAll(items);
		while (!doing.isEmpty()) {
			List<Map<String, Object>> todo = new ArrayList<Map<String, Object>>();
			for (Map<String, Object> item : doing) {
				menus = Menu.findAll(Menu.class, "parentid=?",
						new Object[] { item.get("id") }, "sort");
				if (menus.isEmpty()) {
					continue;
				}
				List<Object> children = new ArrayList<Object>();
				for (Menu menu : menus) {
					Map<String, Object> child = new HashMap<String, Object>();
					child.put("id", menu.getId());
					child.put("text", menu.getName());
					child.put("state", menu.getChildCount() > 0 ? "closed"
							: "open");
					children.add(child);

					todo.add(child);
				}
				item.put("children", children.toArray(new Object[children
						.size()]));
			}
			doing = todo;
		}

		node.put("children", items.toArray(new Object[items.size()]));
		return new JsonView(result);
	}

	public View getMenuItems(int page, int rows, String q, int t, String sort,
			String order) throws Exception {
		String orderBy = "sort";
		if (sort != null && order != null) {
			orderBy = sort + " " + order;
		}
		String cond = "1=1";
		List<Object> tmpArgs = new ArrayList<Object>();

		cond += " and (parentid = ?)";
		tmpArgs.add(t);
		/**
		 * if (q != null){ cond +=
		 * " and (name like '%"+q+"%' or memo like '%"+q+"%' ) "; }
		 **/

		Object[] args = tmpArgs.toArray();

		long total = Menu.count(Menu.class, cond, args);
		List<Menu> items = Menu.findAll(Menu.class, cond, args, orderBy, rows,
				(page - 1) * rows);

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", total);
		result.put("rows", items);

		return new JsonView(result);
	}

	public View saveMenu(Menu item, String[] rids) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		Integer sort = (Integer) Menu.maximum(Menu.class, "sort", null, null);
		if (sort == null) {
			sort = 1;
		} else {
			sort += 1;
		}
		item.setSort(sort);
		if (item.save()) {
			User user = (User) rbac.getCurrentUser();				
			Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")新建菜单，内容为：" + new JsonView(item));									

			result.put("success", true);
		} else {
			result.put("failure", true);
			result.put("msg", getErrorMsg(item));
		}

		View view = new JsonView(result);
		view.setContentType("text/plain;charset=utf-8");
		return view;
	}

	public View updateMenu(int id, Map<String, Object> params, String[] rids)
			throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		Menu item = Menu.find(Menu.class, id);
		JsonView olditem= new JsonView(item);
		item = Menu.updateModel(item, params);
		if (item.save()) {
			User user = (User) rbac.getCurrentUser();				
			Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")修改菜单，原内容为："+ olditem + "\r\n修改内容为：" + new JsonView(item));										

			result.put("success", true);
		} else {
			result.put("failure", true);
			result.put("msg", getErrorMsg(item));
		}

		View view = new JsonView(result);
		view.setContentType("text/plain;charset=utf-8");
		return view;
	}

	public View destroyMenu(int id) throws Exception {
		Menu item = Menu.find(Menu.class, id);
		User user = (User) rbac.getCurrentUser();				
		Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")删除菜单，内容为：" + new JsonView(item));									

		item.destroy();
		return new JsonView("success:true");
	}

	public View move(int id, String dir) throws Exception {
		Menu item = Menu.find(Menu.class, id);
		Menu target = null;
		if (dir.equals("down")) {
			target = Menu.findFirst(Menu.class, "sort>? and parentid = ?",
					new Object[] { item.getSort(), item.getParentid() },
					"sort asc");
		} else {
			target = Menu.findFirst(Menu.class, "sort<? and parentid = ?",
					new Object[] { item.getSort(), item.getParentid() },
					"sort desc");
		}
		if (target != null) {
			Integer tmp = target.getSort();
			target.setSort(item.getSort());
			target.save();
			item.setSort(tmp);
			item.save();
		}
		return new JsonView("success:true");
	}
}
